package com.tamecode.chapter05.part13;

import com.tamecode.chapter05.part11.sub1.LogonService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * 通过编码方式动态添加 bean
 *
 * @Author: Liqc
 * @Date: 2023/3/7 13:18
 */
@Component
public class UserServiceFactoryBean implements BeanFactoryPostProcessor {


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //①将 ConfigurableListableBeanFactory 转化为 DefaultListableBeanFactory
        // DefaultListableBeanFactory 提供了可扩展配置、循环枚举的功能，可以实现bean的动态注入。
        DefaultListableBeanFactory beanFactory = (org.springframework.beans.factory.support.DefaultListableBeanFactory) configurableListableBeanFactory;
        //②通过BeanDefinitionBuilder创建Bean定义
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(LogonService.class);
        //③设置属性userDao,此属性引用已经定义的 bean:userDao
        beanDefinitionBuilder.addPropertyReference ("userDao","userDao");
        //④注册Bean定义
        beanFactory.registerBeanDefinition("logonService", beanDefinitionBuilder.getRawBeanDefinition());

        //⑤直接注册一个Bean实例
        beanFactory.registerSingleton("logonService2",new LogonService());
    }
}
